<template>
  <div class="hello">
    <div class="opea-column">
      <el-button type="primary" icon="el-icon-plus" @click="open()">{{$t('configMap.createConfigMap.createConfigMap')}}</el-button>
      <el-button type="primary" icon="el-icon-plus" :disabled="removeAllImei.length>0 ? false : true" @click="dialogVisibleAll = true;">{{$t('opea.allDelete')}}</el-button>
      <div class="search-box">
            <div class="search">
                <el-input
                :placeholder="$t('placeholder.imei')"
                v-model="searchVal"
                clearable>
                </el-input>
            </div>
            
            <el-button type="primary" icon="el-icon-search" @click="search()">{{$t('opea.search')}}</el-button>
        </div>
    </div>
    <el-table
      v-loading="loading"
      border
      height="620px"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
      type="selection"
      width="55">
    </el-table-column>
      <el-table-column
        prop=imei
        label="imei"
        width="180">
      </el-table-column>
      <el-table-column
        prop="config_name"
        :label="$t('configMap.table.name')">
      </el-table-column>
      <el-table-column
      :label="$t('opea.opea')"
      width="100">
      <template slot-scope="scope">
        <!-- <el-button type="text" size="small" @click="getInfo(scope.row)">{{$t('opea.edit')}}</el-button> -->
        <el-button type="text" size="small" @click="remove(scope.row)">{{$t('opea.delete')}}</el-button>
      </template>
    </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        layout="total, prev, pager, next"
        :total="pageCount">
      </el-pagination>
    </div>


    <el-dialog :title="$t(formTitle)" :visible.sync="dialogFormVisible" width="800px" :before-close="dialogBeforeClose" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item :label="$t('configMap.form.name')" :label-width="formLabelWidth" prop="name">
          <el-select v-model="form.name" class="my-select">
              <el-option v-for="(v,k) in configSelect" :key="k" :label="v.name" :value="v.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item :label="$t('configMap.form.device')" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            :rows="4"
            v-model="form.imei">
          </el-input>
        </el-form-item> -->

        <!-- 20MB == 20971520 -->
        <el-form-item :label-width="formLabelWidth">
            <el-upload
              class="upload-demo"
              action="/m/u"
              accept="text/plain"
              :before-upload="beforeUploadFile"
              :on-remove="removeFile"
              :multiple="false"
              :limit="1"
              :auto-upload="false"
              ref="upload"
              :file-list="fileList">
              <el-button slot="trigger" size="small" type="primary">{{$t('tip.chooseFile')}}</el-button>
              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">{{$t('tip.uploadServer')}}</el-button>
              <div slot="tip" class="el-upload__tip">{{$t('tip.limit')}}</div>
            </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <my-upload accept="text/plain" handlerFn="handlerChange" @handlerChange="fileChange"></my-upload> -->
        <el-button @click="dialogFormVisible = false">{{$t('opea.cancel')}}</el-button>
        <el-button type="primary" @click="addSubmit()">{{$t('opea.ok')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="$t('delDialog.title')"
      :visible.sync="dialogVisible"
      width="30%">
      <span>{{$t('delDialog.message')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{$t('opea.cancel')}}</el-button>
        <el-button type="primary" @click="del()">{{$t('opea.ok')}}</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="$t('delDialog.title')"
      :visible.sync="dialogVisibleAll"
      width="30%">
      <span>{{$t('delDialog.allMessage')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAll = false">{{$t('opea.cancel')}}</el-button>
        <el-button type="primary" @click="allRemove()">{{$t('opea.ok')}}</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="$t('tip.handleResult')" :visible.sync="dialogv" :before-close="handlerClose1" class="lala">
      <div v-if="down.repeat"><a @click="jump(down.repeat)" target="_blank">{{$t('link.repeat')}}</a></div>
        <ul class="result" v-if="info.data&&info.data.length">
            <li><span></span> {{$t('tip.repeatLength')}}：{{info.data.length}}</li>
            <li><span></span> {{$t('tip.repeatIMEI')}}：</li>
        </ul>
        <div v-if="info.data&&info.data.length" style="margin-bottom:20px;">
          <el-input type="textarea" :rows="5" v-model="infoData"></el-input>
        </div>
      <div v-if="down.error"><a @click="jump(down.error)" target="_blank">{{$t('link.error')}}</a></div>
      <ul class="result" v-if="info.data2&&info.data2.length">
            <li><span></span> {{$t('tip.invalidLength')}}：{{info.data2.length}}</li>
            <li><span></span> {{$t('tip.invalidIMEI')}}：</li>
        </ul>
      <div v-if="info.data2&&info.data2.length">
          <el-input type="textarea" :rows="5" v-model="infoData2"></el-input>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import myUpload from "./upload"
import {resetForm} from '../handle.js'
export default {
  name: 'configMap',
  components:{myUpload},
  data () {
    return {
      tableData:[],
      form:{
        imei:''
      },
      down:{},
      searchVal:'',
      removeId:0,
      removeAllImei:[],
      configSelect:[],
      configId:this.$route.query.id,
      dialogVisible:false,
      dialogDown:false,
      currentPage:1,
      pageCount:0,
      dialogVisibleAll:false,
      formLabelWidth:'120px',
      dialogFormVisible:false,
      formTitle:'config.form.addTitle',
      fileList:[],
      rules:{
        name:[
          {required:true, message: this.$t('validate.select.name'), trigger: 'change'}
        ]
      },
      loading:false,
      info:{data:[],data2:[]},
      dialogv:false
    }
  },
  mounted(){
    this.getTableData('c')
    this.getConfigSelect()
  },
  computed:{
    infoData(){
      return this.info.data.join(',\n')
    },
    infoData2(){
      return this.info.data2.join(',\n')
    }
  },
  watch:{
    searchVal(n){
      if(!n){
        this.getTableData(true)
      }
    },
    dialogFormVisible(n){
      if(!n){
        this.clearFile()
      }
    }
  },
  methods:{
    jump(url){
      window.open(url)
    },
    search(){
      if(this.searchVal){
        this.getTableData(false,true)
      }else{
        this.getTableData(true)
      }
      
    },
    getConfigSelect(){
      this.$axios.get('/m/q/c')
      .then(res=>{
        console.log(res.data)
        this.configSelect = res.data
      })
    },
    getTableData(c,i){
      this.loading = true;
      let url = '/m/q/m'
      if(c || (c&&i)){
        url = url+'?c='+this.configId+'&n='+this.currentPage+'&s=10'
      }else if(i){
        url = url+'?i='+this.searchVal+'&n='+this.currentPage+'&s=10'
      }
      this.$axios.get(url)
      .then(res=>{
        this.loading = false
        this.tableData  = res.data.data
        this.pageCount = res.data.total
      })
    },
    getInfo(row){
      this.formTitle = 'config.form.editTitle'
      this.dialogFormVisible = true;
    },
    open(){
      resetForm(this,'form')
      this.formTitle = 'config.form.addTitle'
      this.form=Object.assign({},{imei:''})
      this.dialogFormVisible = true
      console.log(this.form)
    },
    remove(row){
      this.removeId = row.imei;
      this.dialogVisible = true;
    },
    del(imeiArr){
      let data = [];
      data = imeiArr?imeiArr:[this.removeId]
      this.$axios.delete('/m/d/m',{data:data})
      .then(res=>{
        if(res.data.code == 202){
          this.$message.success(res.data.message)
          this.getTableData('c')
        }
      })
        this.dialogVisible = false;
    },
    allRemove(){
      this.del(this.removeAllImei)
      this.dialogVisibleAll = false
    },
    resetForm(){
        if(this.$refs['form']){
            this.$refs['form'].resetFields();
        }
    },
    fileChange(files){
      var formData = new FormData();
      formData.append('file', files);
      this.$axios.post('/m/u',formData)
      .then(res=>{
        this.form.t = res.data.taskId
      })
    },
    addSubmit(){
      let data = {};
      data.c = this.$route.query.id
      data.t = this.form.t;
      if(!this.form.t){
        delete data.t
        this.$message({message:'请上传文件到服务器'})
        return
      }
        this.$refs['form'].validate(valid=>{
            if(!valid){
                return
            }
            this.down = {};
            this.info = {data:[],data2:[]}
            const loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            this.$axios.post('/m/a/m',data)
            .then(res=>{
              loading.close()
              if(res.data.code == 201){
                let resp = res.data;
                if(resp.duplicated){
                  if(resp.duplicated.url){
                    // this.dialogDown = true;
                    this.down.repeat = resp.duplicated.url || ''
                  }else{
                    this.info.data =  resp.duplicated.data || []
                  }
                    this.dialogv = true;
                }
                if(resp.invalid){
                  if(resp.invalid.url){
                    this.down.error = resp.invalid.url || ''
                  }else{
                    this.info.data2 = resp.invalid.data || []
                  }
                  if(!this.dialogv){
                    this.dialogv = true;
                  }
                }
                if(!resp.invalid && !resp.duplicated){
                  this.$message({message:this.$t('tip.saveSuccess'),type:'success'})
                }
                console.log(this.down)
                console.log(this.info)
                this.getTableData('c')
              }
            })
            .catch(err=>{
              loading.close()
            })
            this.dialogFormVisible = false;
        })
    },
    handleSelectionChange(row){
      this.removeAllImei = [];
      row.forEach((v,k)=>{
        this.removeAllImei[k]=v.imei
      })
      console.log(this.removeAllImei)
    },
    submitUpload(){
      this.$refs.upload.submit();
    },
    beforeUploadFile(file){
      console.log(file)
      if(file.size / 1024 / 1024 > 20){
        this.$message(this.$t('tip.file'),'error');
        return false
      }
      let fd = new FormData();
      fd.append('file',file);//传文件
      this.$axios.post('/m/u',fd).then(res=>{
        console.log(res)
        if(res.status === 200 || res.status === 202){
          if(Array.prototype.isPrototypeOf(res.data)){
            this.form.imei = res.data.join('\n')
          }else{
            this.form = Object.assign({},{name:this.form.name,t:res.data.taskId})
          }
          console.log(this.form)
        }else{
          this.clearFile()
        }
      })
      .catch(err=>{
        if(err.status == 406){
          if(err.data.code == 400007){
            this.$message({message:err.data.message,type:'error'});
          }
        }
      })
      return true;
    },
    clearFile(){
      if(this.$refs['upload']){
        this.$refs['upload'].clearFiles()
      }
    },
    dialogBeforeClose(done){
      this.clearFile()
      done()
    },
    handlerClose1(done){
      this.info = {data:[],data2:[]};
      this.dialogv = false;
      done()
    },
    removeFile(file){
      delete this.form.t
    },
    handleCurrentChange(current){
      this.currentPage = current
      this.getTableData('c')
    }
  }
}
</script>
<style scoped>
.opea-column{
  margin-bottom: 15px;
}
.search-box{
        float: right;
        width: 400px;
        height: auto;
        
    }
    .search{
            display: inline-block;
            width: 300px;
        }
    .add-btn {
        float: right;
    }
    .lala a{
      color: blue;
      cursor: pointer;
      text-decoration: underline
    }
</style>


